  <template>
  <!-- vx公众号充值-->
  <div class="recharge">
    <div class="banner_title">
      <img :src="require('@/assets/images/other/guanbo.png')" alt="">
      <span>充值到账时间可能有一定延迟，到账后无法退款，不可提现。</span>
    </div>
    <div class="van_overlay" v-if="show" @click="click_userid" />
    <div class="uner_list" v-if="user_list.user_id">
      <div><img :src="user_list.head_pic" alt="" /></div>
      <div>
        <div>{{ user_list.nick_name }}</div>
        <div>ID: {{ user_list.perfect_number }}</div>
      </div>
      <div @click="xiugai_userlist">修改</div>
    </div>
    <div class="recharge_my" v-else>
      <div class="roomifo_search">
        <div>
          <input
            type="number"
            v-model="perfectNumber"
            @keyup="blurClick"
            @click="clickinput"
            placeholder="请输入充值用户id"
          />
        </div>
      </div>

      <div class="record" v-if="record" :style="{ height: heighr_ + 'vw' }">
        <div class="record_list">
          <div>最近搜索</div>
          <div @click="close_location">清空</div>
        </div>
        <div class="record_cookien">
          <div v-for="(item, index) in arrlist" :key="index">
            <div @click="open_id(item.perfect_number, item.user_id)">
              <strong>{{ item.perfect_number }}</strong> / {{ item.nick_name }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="recharge_money">
      <p>请选择钻石数量</p>
      <ul class="recharge_buy">
        <li
          v-for="(item, index) in buyList"
          :class="liNum == index ? 'hong' : 'hui'"
          :key="index"
          @click="changeClick(index)"
        >
          <p><img :src="require('@/assets/images/other/zuan.png')" />{{ item.diamond }}</p> 
          <p>￥{{ item.money }}</p>
          <img v-if="liNum == index" :src="require('@/assets/images/other/active_.png')" alt="">
        </li>
      </ul>

      <div class="OtherAmounts"> 
         <input type="number" v-model="num_money" placeholder="点击输入其它充值金额"  oninput="value=value.replace(/[^\d]/g,'')">
         <div v-if="num_money">{{num_money*100}}钻</div>
      </div>

      <p>选择支付方式</p>
      <div class="PaymentMethod">
        <!-- <div :class="isPayment?'border_bott AlipayPayment':'AlipayPayment'" @click="isPayment = true">
        </div> -->
        <div :class="!isPayment?'border_bott WechatPayment':'WechatPayment'" @click="isPayment = false">
          <img :src="require('@/assets/images/other/WechatPayment.png')" alt="">
          <img v-show="!isPayment" :src="require('@/assets/images/other/active_.png')" alt="">
        </div>
      </div>
      <div class="Tips_">
         <span>温馨提示：</span>
         <span> <input type="checkbox" v-bind:checked="isChecked" v-on:click="handleDisabled"/>充值前请确认您已满18周岁，未成年人不允许充值、未成年人不允许打赏，阅读并同意<span @click="topush">《充值服务协议》</span></span>
      </div>
      <div @click="handelPay">充值</div>
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent, reactive, toRefs } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Toast } from 'vant'
import wx from 'weixin-js-sdk'
import { userGetUserbyNumber, indexGetOpenId, userDiamondList, paymentSandRecharge, paymentWxRecharge } from '@/api/recharge'
import { getCookie, removeCookie, setCookie } from '@/util/cookie'
import 'vant/lib/index.css'
export default defineComponent({
    setup() {
        const router: any = useRouter()
        const route: any = useRoute()
        const data = reactive<Record<string, any>>({
            isChecked:true,
            isPayment:false,//微信支付
            myZuan: 0,
            buyList: "",
            liNum: 1,
            clickShow: true,
            show: false,
            copyUrl: "paipaixqkefu",
            isDisabledSubmitBtn: true, //按钮是否禁用
            money: null, //金额
            token: getCookie("token"),
            userId: getCookie("userId"),
            userId_seach: "",
            openId: getCookie("openId"),
            username: "",
            payList: {},
            perfectNumber: null, //31548290
            record: false,
            user_list: {}, //查询到的用户信息
            arrlist: [], //缓存查询数据
            num_money:"",
            list_index:"",//临时保存数据
        })
        const handleDisabled = (): void => {
            data.isChecked = !data.isChecked;
            if(data.isChecked==true){
                data.isDisabled =  true;
            }
            else{
                data.isDisabled =  false;
            }
        }
        const topush = (): void => {
            router.push({
                path: "/rechargeProtocol"
            })
        }
        const click_userid = (): void => {
            data.show = false;
            blurClick();
        }
        const close_location = (): void => {
            data.show = false;
            data.arrlist = [];
            removeCookie("weekDay");
            data.record = false;
        }
        const clickinput = (): void => {
            data.show = true;
            if (getCookie("weekDay")) {
                data.record = true;
                data.arrlist = JSON.parse(getCookie("weekDay"));
            }
        }
        const blurClick = async (): Promise<void> => {
            data.show = false;
            data.record = false;
            let params = {
                perfectNumber: data.perfectNumber,
            }
            const dataRes = await userGetUserbyNumber(params)
            if (dataRes.data.status == 0) {
            data.user_list = dataRes.data.result;
            data.userId_seach = dataRes.data.result.user_id;
            var weekArray = [];
            let obj = {
              perfect_number: dataRes.data.result.perfect_number,
              user_id: dataRes.data.result.user_id,
              nick_name: dataRes.data.result.nick_name,
            };

            //判断cookie是否有值
            if (getCookie("weekDay")) {
              //有值，取出来
              var weekArray2 = JSON.parse(getCookie("weekDay"));
              //判断已有的值和要存的值user_id是否有相同
              var result = weekArray2.find((item: any) => {
                return item.user_id == obj.user_id;
              });
              //不相同
              if (result == undefined) {
                weekArray = weekArray2;
                weekArray.push(obj);
                setCookie("weekDay", JSON.stringify(weekArray), 180);
              }
            } else {
              //cookie为空直接存，不用判断
              weekArray.push(obj);
              setCookie("weekDay", JSON.stringify(weekArray), 180);
            }
            data.perfectNumber = "";
          } else {
            // Toast(res.data.text);
          }
        }
        const getCode = (): void => {
            let codeUrl = "";
            let url = encodeURIComponent( 
                `https://h5.xunyinjiaoyou.com/h5/#${route.path}`
            );
            codeUrl =
                "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx99fdcb4ecf1dbaa7&redirect_uri=" +
                url +
                "&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
            location.href = codeUrl;
        }
        const getOpenID = async (code: string): Promise<void> => {
            const dataRes = await indexGetOpenId({
                code: code
            })
            if (dataRes.data.status == 0) {
                setCookie("openId", dataRes.data.result.openid, 180);
                let token = getCookie("token");
                if (token) {
                    let userId = getCookie("userId");
                    data.userId = userId;
                    data.token = token;
                    getZuan();
                }
            }
        }
        const changeClick = (index: number): void => {
            data.liNum = index;
        }
        const changeinputClick = (): void => {
            data.clickShow = !data.clickShow;
        }
        const getZuan = async(): Promise<void> => {
            let params = {
                userId: 0,
                token: data.token,
            };
            const dataRes = await userDiamondList(params)
            if (dataRes.data.status == 0) {
                data.myZuan = dataRes.data.result.diamond;
                data.buyList = dataRes.data.result.values;
                // this.username = res.data.result.user.nickname;
            } else {
                // location.reload();
            }
        }
        const xiugai_userlist = (): void => {
            data.user_list.user_id = "";
            data.perfectNumber = "";
            data.userId_seach = "";
        }
        const open_id = async (perfect_number: string, user_id: string): Promise<void> => {
            data.show = false;
            data.userId_seach = user_id;
            data.record = false;
            let params = {
                perfectNumber: perfect_number,
            }
            const dataRes = await userGetUserbyNumber(params)
            if (dataRes.data.status == 0) {
                data.user_list = dataRes.data.result;
            }
        }
        const handelPay = async (): Promise<void> => {
            if(!data.isChecked){
                Toast("请先勾选同意按钮")
                return
            }
            if(!data.userId_seach){
                Toast("请输入充值用户id")
                return
            }
            data.isDisabledSubmitBtn = true; //防止用户点击多次
            let openId = getCookie("openId");
            let amount;
            if(data.num_money>0){
                amount = data.num_money;
            }else{
                amount = data.buyList[data.liNum].money;
            }
            if (openId) {
                let arys = {
                    userId: data.userId_seach,
                    amount: amount,
                    source: "gongzhonghao",
                    openId: openId,
                    type: 1,
                }; //参数
                let dataRes: null | any = null
                if (route.path === '/recharge_wx_shande') {
                    dataRes = await paymentSandRecharge(arys)
                } else {
                    dataRes = await paymentWxRecharge(arys)
                }
                
                if (dataRes.data.status === 0) {
                    data.payList = dataRes.data.result;
                    weixinPay()
                }else{
                    Toast(dataRes.data.text);
                }
            } else {
                // Toast("获取失败");
                let url = location.href;
                let codetest = RegExp(/code/);
                if (codetest.test(url)) {
                    //地址中有code值
                    let codeStr = url.split("?")[1].split("&")[0].split("=")[1];
                    getOpenID(codeStr);
                } else {
                //地址中没有code值
                    getCode();
                }
            }
        }
        const weixinPay = (): void => {
            if (typeof wx == "undefined") {
                if ((document as any).addEventListener) {
                    (document as any).addEventListener(
                        "WeixinJSBridgeReady",
                        onBridgeReady(),
                        false
                    );
                } else if ((document as any).attachEvent) {
                    (document as any).attachEvent(
                        "WeixinJSBridgeReady",
                        onBridgeReady()
                    );
                    (document as any).attachEvent(
                        "onWeixinJSBridgeReady",
                        onBridgeReady()
                    );
                }
            } else {
                onBridgeReady();
            }
        }
        const onBridgeReady = (): void => {
            wx.invoke(
                "getBrandWCPayRequest",
                {
                    debug: false,
                    appId: data.payList.appId, //公众号名称，由商户传入
                    timeStamp: route.path === '/recharge_wx_shande' ? data.payList.timeStamp : data.payList.timestamp, //时间戳，自1970年以来的秒数
                    nonceStr: data.payList.nonceStr, //随机串
                    package: data.payList.package,
                    signType: data.payList.signType, //微信签名方式：
                    paySign: data.payList.paySign, //微信签名
                    // jsApiList: ["chooseWXPay"]
                },

                function (res: any) {
                    // alert(res.err_msg);
                    // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                    if (res.err_msg == "get_brand_wcpay_request:ok") {
                        //支付成功后的操作
                        getZuan();
                        Toast("支付成功");
                        // location.href = "http://api.xunyinjiaoyou.com/h5/#/recharge_wx";
                        data.isDisabledSubmitBtn = true;
                    } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
                        //取消支付的操作
                        Toast("取消支付");
                        data.isDisabledSubmitBtn = false; //按钮恢复高亮
                    } else {
                        //支付失败的操作
                        Toast("支付失败");
                        data.isDisabledSubmitBtn = false; //按钮恢复高亮
                    }
                }
            )
        }
        if (!data.openId) {
            //没有openId
            const url = location.href;
            const codetest = RegExp(/code/);
            if (codetest.test(url)) {
                //地址中有code值
                let codeStr = url.split("?")[1].split("&")[0].split("=")[1];
                getOpenID(codeStr);
            } else {
                //地址中没有code值
                getCode();
            }
        }
        getZuan()
        return {
            getZuan,
            topush,
            xiugai_userlist,
            click_userid,
            changeClick,
            changeinputClick,
            getCode,
            close_location,
            handelPay,
            handleDisabled,
            clickinput,
            open_id,
            blurClick,
            ...toRefs(data)
        }
    }
})
</script>

<style lang="less" scoped>
@import './RechargeWxShande.less';
</style>